import axios from "axios";
import router from "@/router";

const request = axios.create({
  baseURL: "http://192.168.10.23:5000",
  timeout: 3000,
});

// json 请求
// request.defaults.headers.post['Content-Type'] = 'application/json;charset=utf-8'

request.interceptors.request.use((config) => {
  // Do something before request is sent
  const token = localStorage.getItem("token");
  if (token) {
    config.headers["Authorization"] = "Bearer " + token;
  }
  return config;
});

request.interceptors.response.use(
  (response) => {
    // Do something with response data
    if (response.data.status === 401 || response.data.status === 402) {
      showDialog({
        title: "温馨提示",
        message: response.data.message,
      }).then(() => {
        // 401 代表 token 时效过期，清除本地存储的 token 并跳转到登录页面
        // 402 代表 账号被其他设备登录，清除本地存储的 token 并跳转到登录页面
        localStorage.clear();
        router.replace("/login");
      });
    }
    return response.data;
  },
  (error) => {
    // Do something with response error
    return Promise.reject(error);
  }
);

export default request;
